package com.rainbow.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rainbow.entity.Token;
import com.rainbow.entity.User;
import com.rainbow.mapper.UserMapper;
import com.rainbow.service.TokenService;
import com.rainbow.service.UserService;
import com.rainbow.utils.ApiUtils;
import com.rainbow.utils.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author rainbow
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private TokenService tokenService;

    @Override
    public Map<String, Object> register(User user) {

        String salt = RandomUtil.randomString(20);
        user.setSalt(salt);
        user.setPassword(ShiroUtils.sha256(user.getPassword(), salt));
        user.setUsername(user.getUsername());

        save(user);
        Map<String, Object> result = new HashMap<>(2);
        result.put("success", true);
        result.put("data", "注册成功");

        return result;
    }

    @Override
    public Map<String, Object> login(User user) {
        Map<String, Object> result = new HashMap<>();
        User info = getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (null == info) {
            result.put("success", false);
            result.put("message", "用户不存在");
            return result;
        }
        if (!info.getPassword().equals(ApiUtils.sha256(user.getPassword(), info.getSalt()))) {
            result.put("success", false);
            result.put("message", "密码错误");
            return result;
        }

        Token token = tokenService.createToken(info.getId());


        result.put("success", true);
        result.put("username", user.getUsername());
        result.put("token", token.getToken());
        result.put("expire", token.getExpireTime().getTime() - System.currentTimeMillis());


        return result;
    }
}
